import { resolve } from 'path/posix'
import { Options } from '../../types/ops'
import { ASTResult } from '../../types/ops'
import { createDir } from '../fs/dir'
import { createFile } from '../fs/file'
import { GenerateClass } from './generateClass'
export class GenerateMd extends GenerateClass {
  content: ASTResult[] | []
  ops: Options | {}

  constructor(content: ASTResult[], ops: Options) {
    super(content, ops)
    this.content = this.eliminateRedundancy()
    this.ops = ops
  }
  run() {
    const outputPath = (this.ops as Options).output
    const mainPath = `${outputPath}/${(this.ops as Options).main}.md`
    const hasRelatedMap = new Map()
    let mainFileContent = ''
    this.content.forEach(content => {
      const hasRelated = this.relatedGrammar(content)
      if (hasRelated) {
        const [title, cont] = this.relatedTitleAndContent(content)
        this.relatedCollAdd(hasRelatedMap, title, cont)
      } else mainFileContent += this.wrap(this.generate(content))
    })

    hasRelatedMap.size && createDir(resolve(outputPath))
    const hasRelatedMapKeys = hasRelatedMap.keys()
    for (let i = 0; i < hasRelatedMap.size; i++) {
      const relatedTitle = hasRelatedMapKeys.next().value
      const item: ASTResult[] = hasRelatedMap.get(relatedTitle)
      // createDir(resolve(`${outputPath}/${relatedTitle}`))
      item.forEach(itemAST => {
        mainFileContent += this.generateHeadline(relatedTitle) + this.relatedLink(this.toLink(itemAST, `/${outputPath}/${itemAST.name}.md`))
        // createFile(resolve(`${outputPath}/${relatedTitle}/${itemAST.name}.md`), this.generate(itemAST))
      })
    }
    // createFile(resolve(mainPath), mainFileContent)
  }
}
